//
//  ChatViewController.m
//  CoreDataToChat_81
//
//  Created by Chris on 15/11/24.
//  Copyright © 2015年 Chris. All rights reserved.
//

#import "ChatViewController.h"
#import "Message.h"
#import "CoreDataManager.h"
#import "ChatCell.h"
#import "Roster.h"
#import "NetworkHandler.h"

@interface ChatViewController ()

@property (nonatomic, strong) NSArray *messageArr;

@property (nonatomic, strong) CoreDataManager *manager;

@end

@implementation ChatViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self reloadDataMessage];
}

// storyboard初始化方法
- (void)awakeFromNib {
    self.manager = [CoreDataManager defaults];
    // 监听receive事件，如果触发该事件，调用reloadMessage方法刷新消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataMessage) name:@"receive" object:nil];
}

- (void)reloadDataMessage {
    self.messageArr = [self.manager selectMessageWithFormat:[NSString stringWithFormat:@"from = '%@' OR to = '%@'", self.roster.name, self.roster.name]];
    
    [self.tableView reloadData];
    
    // 滚动到最后一行
    if (self.messageArr.count != 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.messageArr.count - 1 inSection:0];
        // 以动画的方式滚动到底部最后一行
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messageArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chatReuse" forIndexPath:indexPath];
    
    Message *message = self.messageArr[indexPath.row];
    // 判断消息来源
    // 如果是好友发送来的，左边显示消息内容，右边显示时间，否则反之
    if ([message.from isEqualToString:self.roster.name]) {
        cell.leftLabel.text = message.mes;
        cell.rightLabel.text = message.time;
    }
    else {
        cell.leftLabel.text = message.time;
        cell.rightLabel.text = message.mes;
    }
    
    return cell;
}

- (IBAction)sentAction:(id)sender {
    NSString *mes = @"咩哈哈哈哈";
    NSString *from = @"小六";
    // 先存储到本地
    [self.manager addMessage:mes fromName:from toName:self.roster.name];
    [self reloadDataMessage];
    
    NSString *sendUrl = [NSString stringWithFormat:@"http://172.16.5.38/getui/demo.php?token=%@token&name=%@&message=%@", self.roster.token, from, mes];
    
//    NSLog(@"%@", self.roster.token);
    
    [NetworkHandler connectNetGetDataWithURLString:sendUrl complention:^(id result) {
        NSLog(@"发送成功");
        
    }];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
